# -*- coding: utf-8 -*-

# Copyright (C) 2017 Intel Corporation.  All rights reserved.
# Copyright (c) WanSheng Intelligent Corp. All rights reserved.

#
# Licensed under the Apache License, Version 2.0 (the "License");
#


import json
import traceback
from wa_edge_iot.internals.resource_data_ocf import ResourceDataOCF
from ..model.property_data import PropertyData
from ..model.parser_base import ParserBase
from builtins import str


class OCFDataParser(ParserBase):
    def parse(self, text, fmt):
        if type(text) is not str:
            print("OCFDataParser, text is not string. " + str(type(text)))
            return None
        
        try:
            json_object = json.loads(text)
            if json_object is None:
                return None
            data = ResourceDataOCF(text, fmt)
            
            fixed_key_prm = "prm"
            key_set = list(json_object.keys())
            items = []
            
            if fixed_key_prm in json_object:
                prm_json = json_object[fixed_key_prm]
                prm = prm_json
                data.prm = prm

                
            for key_str in key_set:
                if fixed_key_prm != key_str:
                    property_data = PropertyData(key_str, json_object[key_str])
                    items.append(property_data)

            data.items = items
            data.is_parsed = True
            return data

        except Exception as e:
            print("OCFDataParser parse error:" + str(e))
            print(traceback.format_exc())
            return None
